﻿
using System;
using System.Text;

using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;


namespace DataService.Core.Json
{

    public static class JsonHelper
    {

        /// <summary>
        /// 写入对象，得到Json字符串
        /// </summary>
        /// <param name="value"></param>
        /// <param name="indented">是否缩进。默认false</param>
        /// <param name="nullValue">是否写空值。默认true</param>
        /// <param name="camelCase">是否驼峰命名。默认false</param>
        /// <returns></returns>
        public static String ToJson(this Object value, Boolean indented = false, Boolean nullValue = true, Boolean camelCase = false)
        {
            // 是否中文转义 true:转义 false:不转义
            bool safeEncoder = false;
            //默认情况下，序列化程序会转义所有非 ASCII 字符。 即，会将它们替换为 \uxxxx，其中 xxxx 为字符的 Unicode 代码
            //默认情况下，JsonSerializer出于深度的安全考虑，从而对字符串进行了过度的转义。所以，当使用JsonSerializer对中文进行默认序列化时，就会对中文字符进行转义
            //中文和html为转义
            //中文转义解决办法
            var option = new JsonSerializerOptions();

            if (!safeEncoder)
            {
                option.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
            }
            ////html转义解决办法；安全考虑，非特殊情况禁止使用此配置
            //var option = new JsonSerializerOptions
            //{
            //    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            //};

            option.WriteIndented = indented;
            if (!nullValue) option.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault;
            if (camelCase) option.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;


            string json = JsonSerializer.Serialize(value, option);
            return json;
        }

        /// <summary>
        /// 从Json字符串中读取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="upperLower">true:不区分大小写 false 区分大小写</param>
        /// <returns></returns>
        public static T ToJsonEntity<T>(this String json, bool upperLower = true)
        {
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = upperLower
            };
            var obj = JsonSerializer.Deserialize<T>(json, options);
            return obj;
        }
        /// <summary>
        /// 从Json字符串中读取对象
        /// </summary>
        /// <param name="json"></param>
        /// <param name="type"></param>
        /// <param name="upperLower">true:不区分大小写 false 区分大小写</param>
        /// <returns></returns>
        public static Object ToJsonEntity(this String json, Type type, bool upperLower = true)
        {

            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = upperLower
            };
            object obj = JsonSerializer.Deserialize(json, type, options);
            return obj;
        }

    }



}

